//
//  AwardListViewController.m
//  HongFuShop
//
//  Created by chirui on 2017/9/29.
//  Copyright © 2017年 Shui. All rights reserved.
//

#import "AwardListViewController.h"
#import "AwardListTableViewCell.h"
#import "AwardModel.h"

@interface AwardListViewController ()<UITableViewDelegate,UITableViewDataSource>{


    UITableView * _tableView;
    NSMutableArray * _dataArray;
    
    int _page;
    int _totailPage;
    
    UIView * noBodyView;

    
}

@end

@implementation AwardListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
  
    _page = 1;
    TitleView(@"获奖记录");
    self.view.backgroundColor =[UIColor whiteColor];
    _dataArray = @[].mutableCopy;
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"icon_public_return" target:self action:@selector(back)];
    
    noBodyView = [NothingMessageView creatNothingMessageViewFrame:CGRectMake(WIDTH/2-100, (HEIGHT-64)/2-150, 200, 200) andMessageStr:@"没有相关记录！" onView:nil];
    
    [self creatTableView];
    [self getListData];
}

-(void)back{

    [self.navigationController popViewControllerAnimated:YES];
}

-(void)creatTableView {
    
    _tableView =[[UITableView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) style:UITableViewStyleGrouped];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    
    UIView * view =[[UIView alloc]init];
    _tableView.tableFooterView = view;
    [self.view addSubview:_tableView];
    
    MJRefreshNormalHeader * header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        _page = 1;
        [self getListData];
        
    }];
    _tableView.mj_header = header;
    
    MJRefreshAutoNormalFooter *  footer =[MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _page++;
        [self getListData];
    }];
    
    footer.automaticallyRefresh = YES;
    _tableView.mj_footer =footer;
    _tableView.mj_footer.hidden = NO;
    
    [_tableView registerNib:[UINib nibWithNibName:[AwardListTableViewCell reuseIdentifier] bundle:nil] forCellReuseIdentifier:[AwardListTableViewCell reuseIdentifier]];
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _dataArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 90;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 0.01;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    AwardModel * model = _dataArray[indexPath.row];

    AwardListTableViewCell  * cell = [tableView dequeueReusableCellWithIdentifier:[AwardListTableViewCell reuseIdentifier] forIndexPath:indexPath];
    
     cell.awardModel = model;
    cell.goodsName.frame = CGRectMake(100, 10, WIDTH -200, 20);
    cell.goodsName.numberOfLines =2;
    [cell.goodsName sizeToFit];

    if ([model.status isEqualToString:@"1"]) {
        
        cell.statisLabel.layer.borderColor = [UIColor redColor].CGColor;
        cell.statisLabel.text = @"领取";
        cell.statisLabel.textColor = [UIColor redColor];
    }else {
        
        cell.statisLabel.layer.borderColor = [UIColor grayColor].CGColor;
        cell.statisLabel.text = @"已领取";
        cell.statisLabel.textColor = [UIColor grayColor];
    }
    
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    AwardModel * model = _dataArray[indexPath.row];

    if ([model.status isEqualToString:@"1"]) {
        [self getGoodsDetailsRequestForGoodsId:model.award_id];

    }else {
        
        SHuiMBhudTextTimeStr(@"已领取！");
        
        return;
    }
   
}


-(void)getListData{
    
    
    if (_totailPage != 0) {
        if(_page == _totailPage + 1){
            [_tableView.mj_footer setState: MJRefreshStateNoMoreData];
            
            return ;
        }
    }
    
    NSDictionary * dic = @{
                           @"page":[NSString stringWithFormat:@"%d",_page],
                           @"page_num":@"10",
                           @"user_id":USER_DEFAULTGet(@"user_id"),
                           @"token":USER_DEFAULTGet(@"token")
                           };
    
    //    SHuiMBhubNoTimeStr(@"正在加载...");
    [PostNetWorking postNetWorkingStr:RequestUrlStr(get_awardList_api) andparameters:dic Success:^(id responseObject) {
        SHuiMBHidleYes;
        if (codeSucess) {
            _totailPage = [responseObject[@"datas"][@"total_page"]  intValue];
            
            if (_page==1) {
                
                if (_dataArray) {
                    
                    [_dataArray removeAllObjects];
                }
                
                _dataArray = [AwardModel parsingDataFromResultData:responseObject];
               
            }else {
                
               [_dataArray addObjectsFromArray:[AwardModel parsingDataFromResultData:responseObject]];
                
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                
                
                if (_dataArray.count>0) {
                       noBodyView.hidden =YES;
                    
                    if (_dataArray.count<10) {
                        
                        _tableView.mj_footer.hidden = YES;
                    }else {
                        _tableView.mj_footer.hidden = NO;
                    }
                }else {
                    _tableView.mj_footer.hidden = YES;
                        noBodyView.hidden =NO;
                    
                        [self.view addSubview:noBodyView];
                }
                [_tableView.mj_header endRefreshing];
                [_tableView.mj_footer endRefreshing];
                [_tableView reloadData];
                
            });
            
        }else {
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        
    } failed:^(NSError *error) {
        [_tableView.mj_header endRefreshing];
        SHuiMBHidleYes;
        SHuiMBhudTextTimeStr(@"网络错误请重试！");
    }];
}


-(void)getGoodsDetailsRequestForGoodsId:(NSString *)goods_id{
    
    NSDictionary * dic = @{@"user_id":USER_DEFAULTGet(@"user_id"),
                           @"token":USER_DEFAULTGet(@"token"),
                           @"award_id":goods_id};
    SHuiMBhubNoTimeLoding;
    [PostNetWorking postNetWorkingStr:RequestUrlStr(get_award_api) andparameters:dic Success:^(id responseObject) {
        SHuiMBHidleYes;
        if (codeSucess) {
            
            SHuiMBhudTextTimeStr(@"兑换成功！");
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                _page = 1;
                [self getListData];
                
            });
            
        }else {
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
    } failed:^(NSError *error) {
        SHuiMBHidleYes;
        SHuiMBhudTextNetError;
    }];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
